<template>
	<div>
		<el-card class="!border-none" shadow="never">
			<el-page-header content="用户详情编辑" @back="$router.back()" />
		</el-card>
		<el-card class="!border-none mt-4" shadow="never">
		  <el-tabs v-model="active" class="demo-tabs" @tab-click="handleClick">
			    <el-tab-pane label="基本资料" name="basics">
			        <el-form ref="formUserRef" class="ls-form" :model="userInfo" label-width="120px" :rules="rulesUser">
			        	<el-form-item v-if="userInfo.rank_name == '团长'" label="提货方式" prop="buy_shop_switch">
			        		<el-radio-group v-model="userInfo.buy_shop_switch">
			        			<el-radio label="1">订单自提</el-radio>
			        			<el-radio label="2">快递送货</el-radio>
			        		</el-radio-group>
			        	</el-form-item>
			        	<el-form-item label="用户昵称" prop="nickname">
			        		<el-input class="w-[280px]" v-model="userInfo.nickname" placeholder="请输入用户昵称" clearable />
			        	</el-form-item>
			        	<el-form-item label="用户姓名">
			        		<el-input class="w-[280px]" v-model="userInfo.username" placeholder="请输入姓名" clearable />
			        	</el-form-item>
			        	<el-form-item label="用户手机号">
			        		<el-input class="w-[280px]" v-model="userInfo.phone" placeholder="请输入手机号" clearable />
			        	</el-form-item>
			        	<el-form-item label="用户级别" prop="rank_id">
			        		<el-select class="w-[280px]" v-model="userInfo.rank_id">
			        			<template v-for="(item, index) in gradeList">
			        				<el-option :value="item.id" :label="item.name"> {{item.name}}</el-option>
			        			</template>
			        		</el-select>
			        	</el-form-item>
			        	<el-form-item label="用户消费等级" prop="level_id">
			        		<el-select class="w-[280px]" v-model="userInfo.level_id">
			        			<template v-for="(item, index) in expenditureList">
			        				<el-option :value="item.id" :label="item.name"> {{item.name}}</el-option>
			        			</template>
			        		</el-select>
			        	</el-form-item>
			        	<el-form-item>
			        		<el-button type="success" @click="userInfoConfirm">提交资料修改</el-button>
			        	</el-form-item>
			        </el-form>
			    </el-tab-pane>
				<el-tab-pane label="充值资产" name="asset">
					<div class=" gap-10">
						<div class=" h-[100px] price-box flex justify-center items-center">
							<div>
								<div class="text-center">钱包余额</div>
								<div class="text-center price-text mt-[12px]">
									￥{{ Number(userInfo.balance1).toFixed(2)}}
								</div>
							</div>
						</div>
						<div class="flex-1 price-box flex-col justify-center items-center p-10">
							<el-form ref="rechargeRef" :model="rechargeFormData" :label-position="'right'"
								:rules="rulesRecharge">
								<div class="w-[100%] flex flex-row justify-around gap-2">
									<div class="w-[50%]">

										<el-form-item label="充值类型" prop="type">
											<el-select class="w-[280px]" v-model="rechargeFormData.type">
												<template v-for="(item, index) in rechargeTypeList.list">
													<el-option :value="item.type" :label="item.name">
														{{item.name}}</el-option>
												</template>
											</el-select>
										</el-form-item>
										<el-form-item :label="'充值余额'" prop="amount">
											<div>
												<el-input class="ls-input" v-model="rechargeFormData.amount"
													placeholder="请输入金额"
													onkeydown="if (event.keyCode===13){return false;}">
													<template #append>元</template>
												</el-input>
											</div>
										</el-form-item>
										<el-form-item label="余额充值备注" prop="msg">
											<el-input v-model="rechargeFormData.msg" :autosize="{ minRows: 4 }"
												type="textarea" placeholder="请输入余额充值备注" />
										</el-form-item>
									</div>
								</div>
								<div class="text-center">
									<el-button type="success" @click="rechargeConfirm">提交余额充值</el-button>
								</div>
							</el-form>
						</div>
					</div>
				</el-tab-pane>
				<el-tab-pane label="赠送优惠券" name="coupon">
					<el-form ref="couponRef" :model="couponFormData" :label-position="'right'" :rules="rulesCoupon">
						<div class="w-[100%] flex flex-col justify-around">
							<div class="w-[50%]">
								<el-form-item :label="'赠送数量'" prop="count">
									<div>
										<el-input class="ls-input" v-model="couponFormData.count"
											placeholder="请输入数量" onkeydown="if (event.keyCode===13){return false;}">
										</el-input>
									</div>
								</el-form-item>
							</div>
							<div class="w-[100%]">
								<el-form-item label="选择优惠卷" prop="coupon_id">
									<el-checkbox-group v-model="couponFormData.coupon_id">
										<template v-for="(item, index) in couponList.lists.list">
											<el-checkbox :label="item.id">{{item.name}}</el-checkbox>
										</template>
									</el-checkbox-group>
								</el-form-item>
							</div>
						</div>
						<div class="text-center">
							<el-button type="success" @click="couponConfirm">提交赠送优惠卷</el-button>
						</div>
					</el-form>
				</el-tab-pane>
				<el-tab-pane :label="userInfo.rank_name=='团长'?'切换代理':'切换团长'" name="team">
				  <CutPop :rankName="userInfo.rank_name" ref="goodRef"></CutPop>
				</el-tab-pane>
				<el-tab-pane label="操作" name="button">
					<el-button type="danger"  @click="clearInfo(userInfo)">
					    清除团长信息
					</el-button>
				  <el-button type="danger"  @click="userBidden(userInfo)">
				      {{['激活', '封号'][userInfo.status]}}
				  </el-button>
				  <el-button v-if="userInfo.rank_name == '团长'" type="danger"  @click="disabledUser(userInfo)">
				      禁用积分与提现权限
				  </el-button>
				</el-tab-pane>
		  </el-tabs>
		</el-card>

	</div>
</template>

<script lang="ts" setup name="consumerDetail">
	import { forbiddenUser, userEdit, getRechargeType, recharge, getCouponList, giftCoupon,clearCommunityInfo,redFeature } from "@/api/consumer";
	import { UserRankList, levelAllList } from '@/api/user'
	import type { TabsPaneContext } from 'element-plus'
	import cache from '@/utils/cache'
	import { usePaging } from "@/hooks/usePaging";
	import type { FormInstance, FormRules } from 'element-plus'
	import { rulesUser, rulesRecharge, rulesCoupon } from "./data.js";
	import { useDictOptions } from "@/hooks/useDictOptions";
	import feedback from "@/utils/feedback";
	import CutPop from "./component/CutPop.vue";
	const route = useRoute();
	const userInfo = reactive(cache.get('userInfo'));


	// 修改资料
	// 获取用户级别
	const gradeList = ref([]);
	const { getLists } = usePaging({
		fetchFun: UserRankList
	});
	getLists().then((res) => {
		gradeList.value = res.list.map((_res : any) => {
			return { id: _res.id, name: _res.name }
		})
	});

	// 获取消费级别
	const expenditureList = ref([]);
	const { getLists: getLists2 } = usePaging({
		fetchFun: levelAllList
	});
	getLists2().then((res) => {
		expenditureList.value = res.list.map((_res : any) => {
			return { id: _res.id, name: _res.name }
		})
	})

	const formUserRef = shallowRef<FormInstance>();
	const userInfoConfirm = async () => {
		await feedback.confirm('确定提交资料修改？');
		await formUserRef.value?.validate();
		userEdit({
			uuid: userInfo.id,
			buy_shop_switch: userInfo.buy_shop_switch,
			nickname: userInfo.nickname,
			username: userInfo.username,
			phone: userInfo.phone,
			rank_id: userInfo.rank_id,
			level_id: userInfo.level_id,
		})
	}
	const active = ref("basics");

	const goodRef = shallowRef<FormInstance>();
	const handleClick = (tab: TabsPaneContext, event: Event) => {
	  switch (tab.props.name) {
	    case 'basics':  // 基本资料
	      break;
	    case 'asset':  // 充值资产
	      // goodRef.value?.setFormData(room_id);
	      break;
	    case 'coupon':  // 赠送优惠券
	      // signRef.value?.setFormData(room_id);
	      break;
		case 'team':  // 切换团长
		  goodRef.value?.setFormData(userInfo.id,userInfo.rank_name=='团长'?2:1);
		  break;
	    default:
	      break;
	  }
	}

	// 清除团长信息
	const clearInfo = async (data: object) => {
	    await feedback.confirm('确定清除团长信息？');
	    await clearCommunityInfo({uuid: data.id})
	    getLists();
	};

	// 充值
	const rechargeFormData = reactive({
		uuid: userInfo.id,
		amount: 0,
		type: "",
		msg: "",
	});

// 解禁/禁用用户
const userBidden = async (data: any) => {
    if (data.status) {
        await feedback.confirm('确定禁用该用户？');
        forbiddenUser({
            uuid: data.id,
            type: 0//1 解禁用户 0 禁用用户
        }).then(res => {
            data.status = 0
        })
    } else {
        await feedback.confirm('确定解禁该用户？');
        forbiddenUser({
            uuid: data.id,
            type: 1//1 解禁用户 0 禁用用户
        }).then(res => {
            data.status = 1
        })
    }
};

// 禁用积分与提现权限
const disabledUser = async (data: object) => {
    await feedback.confirm('禁止后该团长以及团长下面无法收到签到积分并且团长无法提现佣金，是否禁用？');
    await redFeature({uuid: data.id, type: 1}); // 操作状态 ( 1 解禁 0 禁用)
    getLists();
};

	// const { optionsData: rechargeTypeList } = useDictOptions<{
	//     lists: any[]
	// }>({
	//     lists: {
	//         api: getRechargeType
	//     }
	// });
	const rechargeTypeList = ref([]);
	getRechargeType().then(res => {
		res.list.forEach((res : { type : number; name : string; }) => {
			if (res.type == 4) {
				res.name = '积分'
			}
		})
		rechargeTypeList.value = res
	})

	const rechargeRef = shallowRef<FormInstance>();
	const rechargeConfirm = async () => {
		await feedback.confirm('确定提交余额充值？')
		await rechargeRef.value?.validate();
		recharge(rechargeFormData).then(res => {
			if (rechargeFormData.type == '1') {
				userInfo.balance1 = Number(userInfo.balance1) + Number(rechargeFormData.amount);
			}
			rechargeRef.value?.resetFields();
		});
	};

	// 优惠卷
	const couponFormData = reactive({
		uuid: userInfo.id,
		coupon_id: [],
		count: "",
	});

	const { optionsData: couponList } = useDictOptions<{
		lists : any[]
	}>({
		lists: {
			api: getCouponList
		}
	});

	const couponRef = shallowRef<FormInstance>();
	const couponConfirm = async () => {
		await feedback.confirm('确定提交赠送优惠卷？')
		await couponRef.value?.validate();
		giftCoupon({
			...couponFormData,
			coupon_id: couponFormData.coupon_id.join(',')
		}).then(res => {
			couponRef.value?.resetFields();
		})
	}
</script>
<style lang="scss" scoped>
	.price-box {
		background-color: rgba(248, 248, 248, 1);
	}

	.price-text {
		color: rgba(16, 16, 16, 1);
		font-size: 18px;
		// font-weight: bold;
	}
</style>
